package com.max.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author max
 * @date 2024年08月23日 17:21
 */
@Component
public class GrayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        boolean isGrayRequest = isGrayRequest(exchange.getRequest());
        // 设置到请求头
        ServerHttpRequest tokenRequest = exchange.getRequest().mutate()
            .header("gray", String.valueOf(isGrayRequest))
            .build();
        ServerWebExchange newServerExchange = exchange.mutate().request(tokenRequest).build();
        return chain.filter(newServerExchange);
    }


    private boolean isGrayRequest(ServerHttpRequest serverHttpRequest) {
        // 正常情况下根据用户手机号，用户id等灰度
        MultiValueMap<String, String> queryParams = serverHttpRequest.getQueryParams();
        return queryParams.containsKey("gray") && "true".equals(queryParams.getFirst("gray"));
    }

    @Override
    public int getOrder() {
        return 10149;
    }
}
